import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import i18next, { t } from 'i18next'
import { atom, useAtom } from 'jotai'
import React, { useState } from 'react'
import { toast } from "sonner";
import faceCmdJson from '@/assets/sampleFaceCmd.json'
import { Textarea } from '@/components/ui/textarea'
import { ScrollArea } from '@/components/ui/scroll-area'
import JsonViewer from '@/components/json-viewer'
import { captureRecordReplySchema } from '@/models/capture-record'
import { ZodError, z } from 'zod'
import { zhCN, en } from 'zod/locales'
import { atomWithStorage } from 'jotai/utils'
import { LogDebug, LogInfo } from '../../wailsjs/runtime/runtime'
import { PostJson } from '../../wailsjs/go/main/App.js'
import { Spinner } from '@/components/ui/spinner'

const httpServerUrl = 'httpServerUrl';

const urlAtom = atomWithStorage<string | null>(httpServerUrl, '');
const responseAtom = atom<string | null>('');
const verdictAtom = atom<string | null>(''); //应答结果验证



export default function HttpServerTest() {
    const [url, setUrl] = useAtom(urlAtom);
    const [response, setResponse] = useAtom(responseAtom);
    const [verdict, setVerdict] = useAtom(verdictAtom);
    const [loading, setLoading] = useState(false);

    const sendCmd = async () => {
        setResponse(null);
        setVerdict(null);
        setLoading(true);
        faceCmdJson['sequence_no'] += 1; //每次发送前增加序号
        faceCmdJson['cap_time'] = (new Date()).toISOString().replace('T', ' ').slice(0, -5); //更新抓拍时间为当前时间
        try {
            const json = JSON.stringify(faceCmdJson);
            LogInfo(`Sending to ${url}: ${json}`);
            const resJson = await PostJson(url!, json);
            LogInfo(`Received: ${resJson}`);
            setResponse(resJson);
            const data = await JSON.parse(resJson);
            try {
                captureRecordReplySchema.parse(data);
                var errorMsg = '';
                if (data['sequence_no'] !== faceCmdJson['sequence_no']) {
                    errorMsg += `${t('seqNoNotEqual')}\n`;
                }
                if (data['cap_time'] !== faceCmdJson['cap_time']) {
                    errorMsg += `${t('capTimeNotEqual')}\n`;
                }
                setVerdict(errorMsg ? errorMsg : `${t('typeValidationPassed')}`);
            } catch (e) {
                if (e instanceof ZodError) {
                    LogInfo(i18next.language)
                    i18next.language === 'zh' ? z.config(zhCN()) : z.config(en());
                    setVerdict(z.prettifyError(e));
                } else {
                    setVerdict((e as any).message);
                }
            }
        } catch (error) {
            toast((error as any).toString());
        } finally {
            setLoading(false);
        }

    };

    return (
        <div className='flex flex-col h-full gap-2 '>
            <p className='p-2 text-sm text-gray-400'>{t('httpSvrTestDesc')}</p>
            <div className='flex flex-row items-center gap-1'>
                <Label className='mr-1' >{t('httpSvrUrl')}</Label>
                <Input className='flex-1' placeholder='http://api.example.com/your/api' value={url ?? ''} onInput={v => setUrl(v.currentTarget.value)} />
                <Button className='ml-2' disabled={!url || loading} onClick={sendCmd}> {loading && <Spinner className='size-2' />} {t('send-command')}</Button>
            </div>
            <div className='flex flex-row flex-1 gap-1 overflow-y-auto'>
                <ScrollArea className='flex-1 border rounded'>
                    {response && <JsonViewer data={JSON.parse(response)}></JsonViewer>}
                </ScrollArea>
                <Textarea value={verdict ?? ''} className='flex-1 focus-visible:ring-0'></Textarea>
            </div>
        </div>
    )
}
